import Vue from 'vue'

// 导入路由模块
import VueRouter from 'vue-router'

// 引入子组件
import Login from '@/components/login/Login.vue'
import Home from '@/components/home/Home.vue'
import Users from '@/components/users/Users.vue'
import Roles from '@/components/roles/Roles.vue'
import Rights from '@/components/rights/Rights.vue'
import Categories from '@/components/categories/Categories.vue'
import Goods from '@/components/goods/Goods.vue'
import GoodsAdd from '@/components/goods-add/GoodsAdd.vue'

// 安装
Vue.use(VueRouter)

// 实例化路由
const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/home',
      name: 'home',
      component: Home,
      children: [
        {
          path: '/users',
          component: Users
        },
        {
          path: '/roles',
          component: Roles
        },
        {
          path: '/rights',
          component: Rights
        },
        {
          path: '/categories',
          component: Categories
        },
        {
          path: '/goods',
          component: Goods
        },
        {
          path: '/goods-add',
          component: GoodsAdd
        }
      ]
    }
  ]
})

// 导航守卫
// 参数1 : to 目标路由对象
// 参数2 : from 来源路由对象
// 参数3 : next() 下一步
router.beforeEach((to, from, next) => {
  // 1. 判断是不是登录页面
  // 是登录页面
  if (to.path === '/login') {
    next()
  } else {
    // 不是登录页面
    // 2. 判断 是否登录过
    let token = localStorage.getItem('token')
    token ? next() : next('/login')
  }
})

// 导出
export default router
